package com.liming.file.controller;

import com.liming.common.exception.BusinessException;
import com.liming.common.result.LMResult;
import com.liming.common.util.AliOssUtils;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

/**
 * @author liming
 * @date 2025/5/16
 */
@Slf4j
@RestController
@AllArgsConstructor
@Tag(name = "阿里文件上传-Service")
@RequestMapping("/service/ali")
public class AliController {

    @PostMapping(value = "upload_oss", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public LMResult<String> uploadOss(@RequestPart MultipartFile file) {
        try {
            // 原始文件名
            String originalFilename = file.getOriginalFilename();
            // 截取原始文件名的后缀 name.png
            int index = originalFilename.lastIndexOf(".");
            String extension = originalFilename.substring(index);
            // 构造新文件名称
            String objectName = UUID.randomUUID() + extension;
            String filePath = AliOssUtils.uploadFile(objectName, file.getInputStream());
            return LMResult.success(filePath);
        } catch (Exception e) {
            log.error("上传文件失败", e);
            throw new BusinessException("上传文件失败");
        }
    }
}
